#@tool
class_name FeelEmoji
extends TextureRect

@export var animated_sprite: AnimatedSprite2D
@export var emoji: Texture2D

@export_group("Split Emojis")
@export var emoji_textures: Texture2D
@export var split: Vector2 = Vector2(32, 32)
@export var emoji_list: Array[AtlasTexture] = []
#@export_tool_button("split_func")
var split_task: Callable = start_split
func start_split():
	# 编辑器自动脚本部分
	if Engine.is_editor_hint():
		if emoji_textures != null:
			_auto_split_textures(emoji_textures)
			emoji = emoji_list[0]
		pass
	pass

static var instance: FeelEmoji


func _ready() -> void:
	# 进入游戏时
	if !Engine.is_editor_hint(): 
		instance = self
		self_show_emoji(0)
	pass

func _process(delta: float) -> void:
	pass


static func show_emoji(emoji_index: int) -> void: 
	if !instance: return
	instance.self_show_emoji(emoji_index)
	pass
func self_show_emoji(emoji_index: int) -> void: 
	emoji = emoji_list.get(emoji_index)
	pass

# 自动拆分纹理的方法
func _auto_split_textures(value: Texture2D) -> void:
	# 检查纹理是否是压缩纹理
	var image: Image
	if value is CompressedTexture2D:
		# 如果是压缩纹理，解压并转换为 Image
		image = value.get_image()  # get_data() 会自动解压纹理
	else:
		# 如果是普通纹理，直接获取图像数据
		image = value.get_data()

	# 获取图像的宽高
	var texture_width = image.get_width()
	var texture_height = image.get_height()

	# 清空 emoji_list，确保拆分前数组是空的
	emoji_list.clear()

	# 根据拆分的尺寸进行拆分
	for y in range(0, texture_height, split.y):
		for x in range(0, texture_width, split.x):
			# 定义拆分的区域
			var rect = Rect2(x, y, split.x, split.y)

			# 检查拆分区域是否超出原始纹理的边界
			if rect.position.x + rect.size.x > texture_width:
				rect.size.x = texture_width - rect.position.x
			if rect.position.y + rect.size.y > texture_height:
				rect.size.y = texture_height - rect.position.y

			# 创建新的 AtlasTexture 对象
			var atlas_texture = AtlasTexture.new()
			atlas_texture.atlas = value  # 设置图集为当前纹理
			atlas_texture.region = rect  # 设置区域为拆分的区域

			# 将新的 AtlasTexture 添加到 emoji_list 中
			emoji_list.append(atlas_texture)

	print("Texture split into", emoji_list.size(), "emoji textures.")
